package cn.jwm.org.controller;

import cn.jwm.org.domain.Department;
import cn.jwm.org.query.DepartmentQuery;
import cn.jwm.org.service.IDepartmentService;
import cn.jwm.utils.AjaxResult;
import cn.jwm.utils.PageList;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Resource
    private IDepartmentService iDepartmentService;

    @DeleteMapping("/{id}")
    public AjaxResult deleteByID( @PathVariable("id")Long id){
        try {
        iDepartmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }
    @GetMapping("/{id}")
    public AjaxResult loadById(@PathVariable("id")Long id){
        try {
            Department byId = iDepartmentService.getById(id);
            return AjaxResult.me().setDataObj(byId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败!"+e.getMessage());
        }
    }

    @GetMapping
    public AjaxResult loadAll(){
        try {
            List<Department> all = iDepartmentService.getAll();
            return AjaxResult.me().setDataObj(all);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败!"+e.getMessage());
        }
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            // 判断ID有没有值
            if(Objects.isNull(department.getId())){
                // 新增
               iDepartmentService.add(department);
            }else{
                // 修改
               iDepartmentService.upData(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存失败!"+e.getMessage());
        }
    }
    @PostMapping
    public AjaxResult pageGet(@RequestBody DepartmentQuery query){
        try {
            PageList<Department> page = iDepartmentService.page(query);
            return AjaxResult.me().setDataObj(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.me().setSuccess(false).setMessage("分页查询失败!");
    }

    @PatchMapping
    public AjaxResult patch(@RequestBody List<Long> ids){
        try {
            iDepartmentService.patchDelete(ids);
            return AjaxResult.me().setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败!"+e.getMessage());
        }
    }
    }

